package com.secxiot.consumer.utils;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.exception.BaseException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class RemindIdCardUtil {
    private static Logger LOG = LoggerFactory.getLogger(RemindIdCardUtil.class);

    private static String APP_KEY = "203780132";
    private static String APP_SECRET = "mxma56gvx845uxu5fge2uettc8qgt1e7";
    private static String APP_CODE = "73c023de72da42fc8b16eb9d45d135d5";
    private static String BASE_URL = "https://naidcard.market.alicloudapi.com";


    public static boolean checkName(String idCardNo, String name) throws BaseException {
        if (StringUtils.isBlank(idCardNo)) {
            throw new BaseException(ServerStatusEnum.VALID_IDCARD_ERROR);
        }
        if (StringUtils.isBlank(name)) {
            throw new BaseException(ServerStatusEnum.VALID_IDCARD_ERROR);
        }
        if (!IdcardUtil.isValidCard(idCardNo)) {
            throw new BaseException(ServerStatusEnum.VALID_IDCARD_ERROR);
        }
/*
        String path = "/nidCard";
        HashMap<String, Object> paramMap = new HashMap<>();
        String result = HttpRequest.get(BASE_URL + path + "?idCard=" + idCardNo + "&name=" + name)
                //头信息，多个头信息多次调用此方法即可
                .header("Authorization", "Basic " + APP_CODE)
                .timeout(20000)//超时，毫秒
                .execute().body();
        LOG.info("获取身份校验响应：\n" + result);
        JSONObject jsonObject = JSON.parseObject(result);
        String status = jsonObject.getString("status");
        if ("01".equals(status)) {
            return true;
        }
*/

        String host = "https://naidcard.market.alicloudapi.com";
        String path = "/nidCard";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("idCard", idCardNo);
        querys.put("name", name);
        /**
         * 重要提示如下:
         * HttpUtils请从
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
         * 或者直接下载：
         * http://code.fegine.com/HttpUtils.zip
         * 下载
         *
         * 相应的依赖请参照
         * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
         * 相关jar包（非pom）直接下载：
         * http://code.fegine.com/aliyun-jar.zip
         */


        try {
            HttpResponse response = null;
            try {
                response = HttpUtils.doGet(host, path, method, headers, querys);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                throw new BaseException(ServerStatusEnum.IDCARD_SERVICE_ERROR);
            }
            LOG.info(response.toString());
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                JSONObject httpEntity = getHttpEntity(response);
                if (httpEntity != null && "01".equals(httpEntity.getString("status"))) {
                    return true;
                } else {
                    LOG.info(httpEntity.toString());
                    return false;
                }
            } else {
                LOG.info(EntityUtils.toString(response.getEntity()));
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new BaseException(ServerStatusEnum.IDCARD_SERVICE_ERROR);
        }
        return  false;
    }

    public static JSONObject getHttpEntity(HttpResponse response) {

        String line = null;
        JSONObject resultJsonObject = null;
        StringBuilder entityStringBuilder = new StringBuilder();
        try {
            BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"),8*1024);
            while ((line=b.readLine())!=null) {
                entityStringBuilder.append(line);
            }
            resultJsonObject = JSON.parseObject(entityStringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultJsonObject;

    }

}
